package util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SaveFile {
	private static final int BUFFER_SIZE = 100 * 1024;

	public void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				int len = 0;
				while ((len = in.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getDateStr() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return sdf.format(new Date());
	}

	public String save(String fileName, File file, String flag) {
		String temp = "d:/itamAttachment/" + flag + "/" + getDateStr() + "/"+System.currentTimeMillis()+"/";
		File dir = new File("" + temp);
		if (!dir.exists())
			dir.mkdirs();
		temp = temp + fileName;
		copy(file, new File("" + temp));
		return temp;
	}

	public String save2Server(String fileName, File file, String path) {
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		path = path + fileName;
		copy(file, new File(path));
		return path;
	}
	
	public String savePic(String fileName, File file, String path) {
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		path = path +"\\"+ fileName;
		copy(file, new File(path));
		return path;
	}
	
	public String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos).toLowerCase();
	}
	
	public String saveTemp(String fileName, File file, String flag) {
		String temp = "d:/itamAttachment/";
		File dir = new File("" + temp);
		if (!dir.exists())
			dir.mkdirs();
		temp = temp + fileName;
		copy(file, new File("" + temp));
		return temp;
	}

}
